<template>
  <div class="tools-detail-page">

   <div class="search-page">
      <div class="page-header">
        <h1 class="page-title">搜索结果: {{ oldQuery }}</h1>
        
        <!-- 搜索框 -->
        <div class="search-box-container">
          <div class="search-wrapper">
            <div class="search-input-group">
              <SearchOutlined class="search-icon" />
              <input
                v-model="searchQuery"
                type="text"
                placeholder="搜索AI工具、教程、资讯..."
                class="search-input"
                @keyup.enter="handleSearch"
              >
              <button class="search-btn" @click="handleSearch">
                搜索
              </button>
            </div>
          </div>
        </div>

        <!-- 热门搜索 -->
        <div class="hot-searches">
          <span class="hot-searches-label">热门搜索：</span>
          <div class="hot-search-tags">
            <span
              v-for="tag in hotSearchTags"
              :key="tag"
              class="hot-search-tag"
              @click="handleHotSearch(tag)"
            >
              {{ tag }}
            </span>
          </div>
        </div>
      </div>

      <!-- 搜索结果统计 -->
      <div v-if="loading" class="search-loading">
        <div class="loading-content">
          <div class="loading-spinner"/>
          <p class="loading-text">正在搜索中...</p>
        </div>
      </div>
      <div v-else-if="list.length > 0" class="search-stats">
        找到 {{ list.length }} 个相关工具
      </div>
      <div v-else-if="oldQuery && !loading" class="no-results">
        <div class="no-results-content">
          <SearchOutlined class="no-results-icon" />
          <p class="no-results-text">未找到与 "{{ oldQuery }}" 相关的工具</p>
          <p class="no-results-suggestion">试试其他关键词或浏览热门搜索</p>
        </div>
      </div>

      <ToolCard :tools="list" />
   </div>

    <!-- 推荐板块 -->
    <div class="related-tools-container">
      <div class="recommended-tools">
        <div class="recommended-header">
          <h3 class="recommended-title">🔥 热门推荐</h3>
          <p class="recommended-subtitle">发现更多优质AI工具，探索人工智能的无限可能</p>
        </div>
        
        <div v-if="recommendedLoading" class="recommended-loading">
          <div class="loading-spinner"/>
          <span>正在为您推荐优质工具...</span>
        </div>
        
        <div v-else-if="recommendedTools.length > 0" class="recommended-list">
          <div
            v-for="tool in recommendedTools"
            :key="tool.toolId"
            class="recommended-item"
            @click="handleRecommendedToolClick(tool)"
          >
            <div class="recommended-item-icon">
              <CustomImage
                :src="tool.localLogoPath"
                :alt="tool.toolName"
                img-class="lazy-image"
                type="logo"
              />
            </div>
            <div class="recommended-item-content">
              <h4 class="recommended-item-title">{{ tool.toolName }}</h4>
              <p class="recommended-item-desc">{{ tool.description }}</p>
              <div class="recommended-item-tags">
                <span
                  v-for="(tagItem, index) in getProcessedTags(tool.tags.slice(0, 2))"
                  :key="`${tagItem.tag}-${index}`"
                  class="recommended-tag"
                  :class="[tagItem.color.bgColor, tagItem.color.textColor]"
                >
                  {{ tagItem.tag }}
                </span>
              </div>
            </div>
          </div>
        </div>
        
        <div v-else class="recommended-empty">
          <div class="empty-icon">🤔</div>
          <p>暂无推荐工具，试试搜索其他关键词吧</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ToolItem } from '~/types/tools'
import { processToolTags, type TagColorCombination } from '~/components/ToolCard/toolUtils'

/**
 * 搜索页面脚本
 * 根据URL参数显示搜索结果，提供搜索功能和热门搜索
 */

// 获取当前路由对象和路由器
const route = useRoute()
const router = useRouter()

// 当前页面数据
const list = ref<ToolItem[]>([])
const loading = ref(false)

// 推荐工具数据
const recommendedTools = ref<ToolItem[]>([])
const recommendedLoading = ref(false)

// 热门搜索标签
const hotSearchTags = ref([
  'ChatGPT', 'AI绘画', 'AI写作', 'AI视频',
  'AI编程', 'AI音乐', 'AI翻译', 'AI设计'
])

// 从路由参数中获取搜索关键词
const { q } = route.query
const oldQuery = ref(q as string || '')
const searchQuery = ref(q as string || '')
    
// 获取搜索结果的方法
const fetchSearchResults = async (query: string) => {
  loading.value = true
  list.value = []
  if (!query.trim()) {
    list.value = []
    loading.value = false
    return
  }
  
  try {
    const { success, data } = await $fetch(`/api/search?q=${query}`)
    if (success && data) {
      list.value = data
    } else {
      list.value = []
    }
  } catch (error) {
    console.error('搜索失败:', error)
    list.value = []
  } finally {
    loading.value = false
  }
}

/**
 * 获取推荐工具
 * 基于热门标签随机获取推荐工具
 */
const fetchRecommendedTools = async () => {
  try {
    recommendedLoading.value = true
    
    // 从热门标签中随机选择2-3个标签进行搜索
    const shuffledTags = [...hotSearchTags.value].sort(() => Math.random() - 0.5)
    const selectedTags = shuffledTags.slice(0, Math.floor(Math.random() * 2) + 2) // 随机选择2-3个标签
    
    // 使用搜索API基于热门标签获取推荐工具
    const searchPromises = selectedTags.map(tag =>
      $fetch(`/api/search?q=${tag}`).catch(() => ({ success: false, data: [] }))
    )
    
    const results = await Promise.all(searchPromises)
    
    // 合并所有搜索结果并去重
    const allTools: ToolItem[] = []
    const toolIds = new Set()
    
    results.forEach(result => {
      if (result.success && result.data && Array.isArray(result.data)) {
        result.data.forEach((tool: ToolItem) => {
          if (!toolIds.has(tool.toolId)) {
            toolIds.add(tool.toolId)
            allTools.push(tool)
          }
        })
      }
    })
    
    // 随机选择6个工具作为推荐
    recommendedTools.value = allTools.sort(() => Math.random() - 0.5).slice(0, 8)
    
  } catch (error) {
    console.error('获取推荐工具失败:', error)
    // 如果基于标签搜索失败，使用备用方案：获取最新工具
    try {
      const { success, data } = await $fetch('/api/tools-with-tags', {
        method: 'POST',
        body: {
          categoryIds: [1], // 默认获取第一个分类
          pageNum: 1,
          pageSize: 10
        }
      })
      
      if (success && data && data.length > 0 && data[0]?.list) {
        recommendedTools.value = data[0].list.sort(() => Math.random() - 0.5).slice(0, 6)
      }
    } catch (backupError) {
      console.error('备用推荐方案也失败了:', backupError)
    }
  } finally {
    recommendedLoading.value = false
  }
}

/**
 * 处理推荐工具标签显示
 */
const getProcessedTags = (tags: string[]): Array<{tag: string, color: TagColorCombination}> => {
  return processToolTags(tags, true)
}

/**
 * 点击推荐工具跳转
 */
const handleRecommendedToolClick = (tool: ToolItem) => {
  navigateTo(`/tool-detail/${tool.toolId}`)
}

// 只有在有搜索参数时才初始加载搜索结果
if (searchQuery.value) {
  fetchSearchResults(searchQuery.value)
}

// 始终加载推荐工具
fetchRecommendedTools()

/**
 * 处理搜索功能
 * 当用户点击搜索按钮或按回车键时执行搜索
 */
const handleSearch = () => {
  if (searchQuery.value === oldQuery.value) {
    fetchSearchResults(searchQuery.value)
    return
  }
  if (searchQuery.value.trim()) {
    // 更新URL参数
    router.push({
      query: { q: searchQuery.value }
    })
  } else {
    message.warning('请输入搜索关键词')
  }
}

/**
 * 处理热门搜索点击
 * 点击热门搜索标签时执行搜索
 */
const handleHotSearch = (tag: string) => {
  searchQuery.value = tag
  handleSearch()
}


watch(
  () => route.query.q,
  (newQuery) => {
    oldQuery.value = newQuery as string
    searchQuery.value = newQuery as string
    fetchSearchResults(newQuery as string)
  }
)
/**
 * 设置页面头部信息
 * 动态设置页面标题，包含搜索关键词
 */
useHead({
  title: `${route.query.q ? `${searchQuery.value} - ` : ''}搜索结果 - AI工具集合，国内外AI工具集导航大全`,
  meta: [
    {
      name: 'description',
      content: route.query.q ? `搜索"${searchQuery.value}"相关的AI工具，包括AI写作、AI绘画、AI视频制作、AI编程等各类人工智能工具推荐和使用指南。` : '搜索AI工具，包括AI写作、AI绘画、AI视频制作、AI编程等各类人工智能工具推荐和使用指南。'
    }
  ]
})
</script>

<style lang="less" scoped>
.tools-detail-page {
  padding: 24px 0;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-title {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 24px;
  background: linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

/* 搜索框样式 */
.search-box-container {
  margin-bottom: 24px;
  display: flex;
  justify-content: center;
}

.search-wrapper {
  width: 100%;
  max-width: 600px;
}

.search-input-group {
  position: relative;
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 25px;
  padding: 12px 20px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);

  &:hover {
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
    transform: translateY(-1px);
  }

  .search-icon {
    font-size: 18px;
    color: var(--text-secondary);
    margin-right: 12px;
  }

  .search-input {
    flex: 1;
    border: none;
    outline: none;
    background: transparent;
    font-size: 16px;
    color: var(--text-color);
    padding: 4px 0;

    &::placeholder {
      color: var(--text-secondary);
    }
  }

  .search-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    padding: 8px 20px;
    border-radius: 20px;
    font-size: 14px;
    cursor: pointer;
    color: white;
    transition: all 0.3s ease;
    margin-left: 12px;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }
  }
}

/* 热门搜索样式 */
.hot-searches {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 32px;

  .hot-searches-label {
    font-size: 14px;
    color: var(--text-secondary);
    font-weight: 500;
  }

  .hot-search-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .hot-search-tag {
    padding: 6px 12px;
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 16px;
    font-size: 13px;
    color: var(--text-color);
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-color: transparent;
      transform: translateY(-1px);
    }
  }
}

/* 搜索结果统计 */
.search-stats {
  text-align: center;
  margin-bottom: 24px;
  font-size: 14px;
  color: var(--text-secondary);
}

/* 加载状态 */
.search-loading {
  text-align: center;
  padding: 60px 20px;
  margin-bottom: 32px;
}

.loading-content {
  max-width: 400px;
  margin: 0 auto;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(102, 126, 234, 0.1);
  border-top: 3px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

.loading-text {
  font-size: 16px;
  color: var(--text-secondary);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 无结果提示 */
.no-results {
  text-align: center;
  padding: 60px 20px;
  margin-bottom: 32px;

  .no-results-content {
    max-width: 400px;
    margin: 0 auto;
  }

  .no-results-icon {
    font-size: 64px;
    color: var(--text-secondary);
    margin-bottom: 16px;
    opacity: 0.5;
  }

  .no-results-text {
    font-size: 18px;
    color: var(--text-color);
    margin-bottom: 8px;
    font-weight: 500;
  }

  .no-results-suggestion {
    font-size: 14px;
    color: var(--text-secondary);
  }
}

.page-subtitle {
  font-size: 16px;
  color: var(--text-secondary);
}

/* 暗黑模式样式 */
html.dark {
  .search-input-group {
    background: var(--bg-header);
    border-color: var(--border-light);

    &:hover {
      background: var(--bg-hover-active);
    }

    .search-input {
      color: var(--text-color);

      &::placeholder {
        color: var(--text-secondary);
      }
    }
  }

  .hot-search-tag {
    background: var(--bg-header);
    border-color: var(--border-light);

    &:hover {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }
  }
}
html.dark .mobile-menu-toggle {
  color: var(--text-color);
  svg {
    color: var(--text-color);
  }
}
/* 移动端响应式样式 */
@media (max-width: 768px) {
  .tools-detail-page {
    padding: 15px;
  }

  .page-title {
    font-size: 24px;
    margin-bottom: 20px;
  }

  .search-wrapper {
    max-width: 100%;
  }

  .search-input-group {
    padding: 10px 16px;

    .search-input {
      font-size: 14px;
    }

    .search-btn {
      padding: 6px 16px;
      font-size: 12px;
    }
  }

  .hot-searches {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;

    .hot-search-tags {
      width: 100%;
      justify-content: flex-start;
    }
  }
}

/* 推荐板块样式 */
.related-tools-container {
  margin-top: 48px;
  padding: 0 20px;
}

.recommended-tools {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 32px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  }
}

.recommended-header {
  margin-bottom: 24px;
  text-align: center;
}

.recommended-title {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.recommended-subtitle {
  font-size: 14px;
  color: #666;
}

.recommended-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  flex-direction: column;
  gap: 12px;
}

.recommended-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.recommended-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
  background: rgba(255, 255, 255, 0.5);
  
  &:hover {
    background: rgba(102, 126, 234, 0.05);
    border-color: rgba(102, 126, 234, 0.2);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.recommended-item-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.recommended-item-content {
  flex: 1;
  min-width: 0;
}

.recommended-item-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.recommended-item-desc {
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.recommended-item-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.recommended-tag {
  font-size: 11px;
  padding: 3px 8px;
  border-radius: 10px;
  font-weight: 500;
}

.recommended-empty {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
}

/* 暗黑模式下的推荐板块样式 */
html.dark .recommended-tools {
  background: var(--bg-header);
  border: 1px solid var(--border-color);
}

html.dark .recommended-title {
  background: var(--btn-primary-bg);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

html.dark .recommended-subtitle {
  color: var(--text-secondary);
}

html.dark .recommended-item {
  background: var(--bg-card);
  
  &:hover {
    background: var(--bg-hover);
    border-color: var(--primary-color);
  }
}

html.dark .recommended-item-title {
  color: var(--text-color);
}

html.dark .recommended-item-desc {
  color: var(--text-secondary);
}

html.dark .recommended-empty {
  color: var(--text-light);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .related-tools-container {
    padding: 0 15px;
    margin-top: 32px;
  }
  
  .recommended-tools {
    padding: 24px 20px;
  }
  
  .recommended-title {
    font-size: 20px;
  }
  
  .recommended-list {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .recommended-item {
    padding: 12px;
  }
  
  .recommended-item-icon {
    width: 40px;
    height: 40px;
  }
  
  .recommended-item-title {
    font-size: 14px;
  }
  
  .recommended-item-desc {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .recommended-tools {
    padding: 20px 15px;
  }
  
  .recommended-header {
    margin-bottom: 20px;
  }
}
</style>